// ==UserScript==
// @name UserAgentChangeModLite.uc.js
// @namespace http://www.sephiroth-j.de/mozilla/
// @charset     utf-8
// @note  modify by lastdream2013 at 20130616 mino fix
// @note  modify by lastdream2013 at 20130409 sitelist : change SITELIST idx to Name
// @note  modify by lastdream2013 for navigator.userAgent https://g.mozest.com/thread-43428-1-2
// @include chrome://browser/content/browser.xul
// ==/UserScript==
var ucjs_UAChanger = {

	DISPLAY_TYPE : 1, // 0显示列表为radiobox, 1显示为ua图标列表

	//（1）在url后面添加网站，注意用正则表达式
	SITE_LIST : [

		// 在 http://www.google.co.jp/m 伪装成日本DoCoMo手机
		{
			url : "http://www\\.google\\.co\\.jp/m/",
			Name : "iPhone"
		}, //此处添加你需要的useragent的名称
		{
			url : "https?://www\\.icbc\\.com\\.cn/",
			Name : "Firefox10.0"
		}, {
			url : "https?://(?:mybank1?|b2c1)\\.icbc\\.com\\.cn/",
			Name : "Firefox10.0"
		},{
			url : "http://vod\\.kankan\\.com/",
			Name : "Safari - Mac"
		}, //直接可以看kankan视频，无需高清组件

		//添加网站到此结束
	],

	//现有版本firefox的图标
	NOW_UA_IMG : "",
	EXT_FX_LIST_IMG : "",

	//自己在底下添加ua
	UA_LIST : [{
			name : "分隔线",
		}, {
			name : "Firefox10.0",
			ua : "Mozilla/5.0 (Windows NT 6.1; rv:10.0.6) Gecko/20120716 Firefox/10.0.6",
			label : "Firefox10.0",
			img : ""
		}, {
			name : "分隔线",
		},

		//伪装 IE8 - Windows7
		{
			name : "IE8 - Win7", //此处文字显示在右键菜单上，中文字符请转换成javascript编码，否则乱码(推荐http://rishida.net/tools/conversion/)
			ua : "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)",
			label : "IE8", //此处文字显示在状态栏上，如果你设置状态栏不显示图标
			img : ""
		}, {
			name : "分隔线",
		},

		// 伪装 Chrome22.0.1219.0 - Windows7
		{
			name : "Chrome - Win7",
			ua : "Mozilla/5.0 (Windows NT 6.1;) AppleWebKit/537.3 (KHTML, like Gecko) Chrome/22.0.1219.0 Safari/537.3",
			label : "Chrome Win7",
			img : ""
		}, {
			name : "分隔线",
		},
		// 伪装 Chrome -mac
		{  
		  name: "Chrome - Mac",
      ua: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1664.3 Safari/537.36",
      label: "Chrome Mac",
      img: ""
   }, {
		 name : "分隔线",
	 },
	 
	 // 伪装 Chrome -mac
   { 
	   name: "Chrome - linux",
     ua: "Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.462.0 Safari/534.3",
     label: "Chrome linux",
     img: ""
   }, {
		 name : "分隔线",
	 },
   
   //伪装 Opera 10.60
		{
			name : "Opera",
			ua : "Opera/9.80 (Windows NT 6.1; U) Presto/2.6.30 Version/10.60",
			label : "Opera",
			img : ""
		}, {
			name : "分隔线",
		},

		//伪装 Safari - Mac OS X
		{
			name : "Safari - Mac",
			ua : "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_5_8; ja-jp) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16",
			label : "Safari",
			img : ""
		}, {
			name : "分隔线",
		},

		//伪装 iPhone，查询http://www.zytrax.com/tech/web/mobile_ids.html
		{
			name : "iPhone",
			ua : "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_1_2 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7D11 Safari/528.16",
			label : "iPhone",
			img : ""
		}, {
			name : "分隔线",
		},

		//伪装 Apple iPad 2
		{
			name : "Apple iPad 2",
			ua : "Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25",
			label : "Apple iPad 2",
			img : ""
		}, {
			name : "分隔线",
		},
// 伪装 Android Droid
    { 
      name: "Android",
      ua: "Mozilla/5.0 (Linux; U; Android 2.0; en-us; Droid Build/ESD20) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17",
      label: "Android",
      img: ""
    }, {
			name : "分隔线",
		},
		//伪装 Android 4.4.2
		{
		  name : "Android 4.4.2",
			ua : "SAMSUNG-SM-T537A Build/KOT49H) AppleWebKit/537.36 (KHTML like Gecko) Chrome/35.0.1916.141 Safari/537.36",
			label : "Android 4.4.2",
			img : ""
		}, {
			name : "分隔线",
		},
		// 伪装 Nokia E72
    { name: "Nokia",
    ua: "Mozilla/5.0 (SymbianOS/9.3; Series60/3.2 NokiaE72-1/021.021; Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/525 (KHTML, like Gecko) Version/3.0 BrowserNG/7.1.16352",
    label: "Nokia",
    img: ""
    }, {
			name : "分隔线",
		},
		//伪装 日本DoCoMo手机
    { name: "DoCoMo",
    ua: "DoCoMo/1.0/P502i/c10 (Google CHTML Proxy/1.0)",
    label: "DoCoMo",
    img: ""
    }, {
			name : "分隔线",
		},
		//伪装 UC 浏览器
    { 
      name: "UcBrowser",
      ua: "NOKIA5700/ UCWEB7.0.2.37/28/999",
      label:"UcBrowser",
      img:  ""
    }, {
			name : "分隔线",
	  },
		//伪装 Google 爬虫
		{
			name : "Googlebot",
			ua : "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
			label : "Googlebot",
			img : ""
		}, {
			name : "分隔线",
		},
		//伪装 BaiduYun
    {  
      name: "BaiduYun",//此处文字显示在右键菜单上，中文字符请转换成javascript编码，否则乱码(推荐http://rishida.net/tools/conversion/)
      ua: "netdisk;4.4.0.6;PC;PC-Windows;6.2.9200;WindowsBaiduYunGuanJia",
      label: "BaiduYun",//此处文字显示在状态栏上，如果你设置状态栏不显示图标
      img: ""
    }, {
			name : "分隔线",
		},  
		// 添加ua，到此结束
	],

	UANameIdxHash : [],

	// ----- 下面设置开始 -----
	// defautl: ステータスバーの右端に表示する
	TARGET : null, // 定义一个target，用来调整状态栏顺序,null为空

	ADD_OTHER_FX : true, // true:自动添加其他版本firefox的ua  false:不添加
	
	//2种版本firefox，下面请勿修改
	EXT_FX_LIST : [{
			name : "Firefox4.0",
			ua : "Mozilla/5.0 (Windows; Windows NT 6.1; rv:2.0b2) Gecko/20100720 Firefox/4.0b2",
			label : "Fx4.0",
			img : ""
		}, {
			name : "Firefox3.6",
			ua : "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8",
			label : "Fx3.6",
			img : ""
		},
	],
	// ----------------------
	// UA リストのインデックス
	def_idx : 0,
	Current_idx : 0,

	// 初期化
	init : function () {
		this.mkData(); // UA データ(UA_LIST)を作る
		this.mkPanel(); // パネルとメニューを作る
		this.setSiteIdx();
		// Observer 登録
		var os = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
		os.addObserver(this, "http-on-modify-request", false);
		os.addObserver(this.onDocumentCreated, "content-document-global-created", false);
		// イベント登録
		var contentArea = document.getElementById("appcontent");
		contentArea.addEventListener("load", this, true);
		contentArea.addEventListener("select", this, false);
		var contentBrowser = this.getContentBrowser();
		contentBrowser.tabContainer.addEventListener("TabClose", this, false);
		window.addEventListener("unload", this, false);
	},
	onDocumentCreated : function (aSubject, aTopic, aData) {
		var aChannel = aSubject.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIWebNavigation).QueryInterface(Ci.nsIDocShell).currentDocumentChannel;
		if (aChannel instanceof Ci.nsIHttpChannel) {
			var navigator = aSubject.navigator;
			var userAgent = aChannel.getRequestHeader("User-Agent");
			if (navigator.userAgent != userAgent)
				Object.defineProperty(XPCNativeWrapper.unwrap(navigator), "userAgent", {
					value : userAgent,
					enumerable : true
				});
		}
	},
	// UA データを作る
	mkData : function () {
		var ver = this.getVer(); // 現在使っている Firefox のバージョン
		// 現在使っている Firefox のデータを作る
		var tmp = [];
		tmp.name = "Firefox" + ver;
		tmp.ua = "";
		tmp.img = this.NOW_UA_IMG;
		tmp.label = "Fx" + (this.ADD_OTHER_FX ? ver : "");
		this.UA_LIST.unshift(tmp);
		// Fx のバージョンを見て UA を追加する
		if (this.ADD_OTHER_FX) {
			if (ver == 3.6) { // Fx3.6 の場合 Fx4 を追加する
				this.EXT_FX_LIST[0].img = this.EXT_FX_LIST_IMG;
				this.UA_LIST.push(this.EXT_FX_LIST[0]);
			} else { // Fx3.6 以外では Fx3.6 を追加する
				this.EXT_FX_LIST[1].img = this.EXT_FX_LIST_IMG;
				this.UA_LIST.push(this.EXT_FX_LIST[1]);
			}
		}
		// 起動時の UA を 初期化 (general.useragent.override の値が有るかチェック 07/03/02)
		var preferencesService = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("");
		if (preferencesService.getPrefType("general.useragent.override") != 0) {
			for (var i = 0; i < this.UA_LIST.length; i++) {
				if (preferencesService.getCharPref("general.useragent.override") == this.UA_LIST[i].ua) {
					this.def_idx = i;
					break;
				}
			}
		}
	},
	// UA パネルを作る
	mkPanel : function () {
		var uacPanel = document.createElement("toolbarbutton");
		uacPanel.setAttribute("id", "uac_statusbar_panel");
		uacPanel.setAttribute("class", "toolbarbutton-1 chromeclass-toolbar-additional");
		uacPanel.setAttribute("type", "menu");
		// css 解决按钮定义在urlbar-icons撑大地址栏，变宽……
		document.insertBefore(document.createProcessingInstruction('xml-stylesheet', 'type="text/css" href="data:text/css;utf-8,' + encodeURIComponent(
		'\
		#uac_statusbar_panel {\
		  -moz-appearance: none !important;\
		  border-style: none !important;\
		  border-radius: 0 !important;\
		  padding: 0 3px !important;\
		  margin: 0 !important;\
		  background: transparent !important;\
		  box-shadow: none !important;\
		  -moz-box-align: center !important;\
		  -moz-box-pack: center !important;\
		  min-width: 18px !important;\
		  min-height: 18px !important;\
		          }\
		#uac_statusbar_panel > .toolbarbutton-icon {\
			max-width: 18px !important;\
		    padding: 0 !important;\
		    margin: 0 !important;\
		}\
		#uac_statusbar_panel dropmarker{display: none !important;}\
		    ') + '"'), document.documentElement);

		uacPanel.setAttribute("image", this.UA_LIST[this.def_idx].img);
		uacPanel.style.padding = "0px 2px";

		var toolbar = document.getElementById("urlbar-icons");
		if (this.TARGET != null) { // default から書き換えている場合
			this.TARGET = document.getElementById(this.TARGET);
		}
		toolbar.insertBefore(uacPanel, this.TARGET);
		// UA パネルのコンテクストメニューを作る
		var PopupMenu = document.createElement("menupopup");
		PopupMenu.setAttribute("id", "uac_statusbar_panel_popup");
		for (var i = 0; i < this.UA_LIST.length; i++) {
			if (this.UA_LIST[i].name == "分隔线") {
				var mi = document.createElement("menuseparator");
				PopupMenu.appendChild(mi);
			} else {
				var mi = document.createElement("menuitem");

				mi.setAttribute('label', this.UA_LIST[i].name);
				mi.setAttribute('tooltiptext', this.UA_LIST[i].ua);
				mi.setAttribute('oncommand', "ucjs_UAChanger.setUA(" + i + ");");

				if (this.DISPLAY_TYPE) {
					mi.setAttribute('class', 'menuitem-iconic');
					mi.setAttribute('image', this.UA_LIST[i].img);
				} else {
					mi.setAttribute("type", "radio");
					mi.setAttribute("checked", i == this.def_idx);
				}
				if (i == this.def_idx) {
					mi.setAttribute("style", 'font-weight: bold;');
					mi.style.color = 'red';
				} else {
					mi.setAttribute("style", 'font-weight: normal;');
					mi.style.color = 'black';
				}
				mi.setAttribute("uac-generated", true);
				PopupMenu.appendChild(mi);
			}
		}
		uacPanel.addEventListener("popupshowing", this, false);
		uacPanel.appendChild(PopupMenu);

		// パネルの変更を可能にする
		uacPanel.setAttribute("context", "uac_statusbar_panel_popup");
		uacPanel.setAttribute("onclick", "event.stopPropagation();");
	},
	// URL 指定で User-Agent の書き換え(UserAgentSwitcher.uc.js より)
	observe : function (subject, topic, data) {
		if (topic != "http-on-modify-request")
			return;
		var http = subject.QueryInterface(Ci.nsIHttpChannel);
		for (var i = 0; i < this.SITE_LIST.length; i++) {
			if (http.URI && (new RegExp(this.SITE_LIST[i].url)).test(http.URI.spec)) {
				var idx = this.SITE_LIST[i].idx;
				http.setRequestHeader("User-Agent", this.UA_LIST[idx].ua, false);
			}
		}
	},
	// イベント・ハンドラ
	handleEvent : function (aEvent) {
		var contentBrowser = this.getContentBrowser();
		var uacPanel = document.getElementById("uac_statusbar_panel");
		var uacMenu = document.getElementById("uac_statusbar_panel_popup");
		switch (aEvent.type) {
		case "popupshowing": // コンテクスト・メニュー・ポップアップ時にチェック・マークを更新する
			var menu = aEvent.target;
			for (var i = 0; i < menu.childNodes.length; i++) {
				if (i == ucjs_UAChanger.Current_idx) {
					menu.childNodes[i].setAttribute("style", 'font-weight: bold;');
					menu.childNodes[i].style.color = 'red';
					if (!this.DISPLAY_TYPE)
						menu.childNodes[i].setAttribute("checked", true);
				} else {
					menu.childNodes[i].setAttribute("style", 'font-weight: normal;');
					menu.childNodes[i].style.color = 'black';
				}
			}
			break;
		case "load": // SITE_LIST に登録された URL の場合
		case "select":
		case "TabClose":
			for (var i = 0; i < ucjs_UAChanger.SITE_LIST.length; i++) {
				if ((new RegExp(this.SITE_LIST[i].url)).test(contentBrowser.currentURI.spec)) {
					var idx = this.SITE_LIST[i].idx;
					this.setImage(idx);
					return;
				}
			}
			this.setImage(this.def_idx);

			break;
		case "unload": // 終了処理
			var os = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
			os.removeObserver(this, "http-on-modify-request");
			os.removeObserver(this.onDocumentCreated, "content-document-global-created");
			var contentArea = document.getElementById("appcontent");
			contentArea.removeEventListener("load", this, true);
			contentArea.removeEventListener("select", this, false);
			if (contentBrowser)
				contentBrowser.tabContainer.removeEventListener("TabClose", this, false);
			uacMenu.removeEventListener("popupshowing", this, false);
			window.removeEventListener("unload", this, false);
			break;
		}
	},
	// 番号を指定して UA を設定
	setUA : function (i) {
		var preferencesService = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("");
		if (i == 0) { // オリジナル UA にする場合
			// 既にオリジナル UA の場合は何もしない
			if (preferencesService.getPrefType("general.useragent.override") == 0)
				return;
			preferencesService.clearUserPref("general.useragent.override");
		} else { // 指定した UA にする場合
			preferencesService.setCharPref("general.useragent.override", this.UA_LIST[i].ua);
		}
		this.def_idx = i;
		this.setImage(i);
	},
	// UA パネル画像とツールチップを設定
	setImage : function (i) {
		var uacPanel = document.getElementById("uac_statusbar_panel");

		uacPanel.setAttribute("image", this.UA_LIST[i].img);
		uacPanel.style.padding = "0px 2px";

		this.Current_idx = i;
	},
	// アプリケーションのバージョンを取得する(Alice0775 氏のスクリプトから頂きました。)
	getVer : function () {
		var info = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULAppInfo);
		var ver = parseInt(info.version.substr(0, 3) * 10, 10) / 10;
		return ver;
	},
	setSiteIdx : function () {
		for (let i = 0; i < this.UA_LIST.length; i++) {
			this.UANameIdxHash[this.UA_LIST[i].name] = i;
		}
		for (let j = 0; j < this.SITE_LIST.length; j++) {
			var uaName = this.SITE_LIST[j].Name;
			if (this.UANameIdxHash[uaName]) {
				this.SITE_LIST[j].idx = this.UANameIdxHash[uaName];

			} else {
				this.SITE_LIST[j].idx = this.def_idx;

			}
		}
	},
	// 現在のブラウザオブジェクトを得る。
	getContentBrowser : function () {
		var windowMediator = Cc["@mozilla.org/appshell/window-mediator;1"]
			.getService(Ci.nsIWindowMediator);
		var topWindowOfType = windowMediator.getMostRecentWindow("navigator:browser");
		if (topWindowOfType)
			return topWindowOfType.document.getElementById("content");
		return null;
	}
}
ucjs_UAChanger.init();
